package com.authine.cloudpivot.ext.kingdee.work;

import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeOrderGoodsReceived;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeOrderGoodsRefund;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeReturnGeneration;
import com.authine.cloudpivot.ext.dto.voucher.Voucher;

import com.authine.cloudpivot.ext.enums.kingdee.AccountingDimensionEnum;
import com.authine.cloudpivot.ext.enums.kingdee.BusinessType;
import com.authine.cloudpivot.ext.enums.kingdee.FAccountIdEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: liwei
 * @DateTime: 2021/7/16
 * @Description: TODO
 */
@Slf4j
public class OrderWork extends BaseWork {


    /**
     * 收货生成凭证
     * 2.1外购入库和3.1销售出库
     *
     * @param ogreList
     */
    public SingleResponse<List<Voucher>> receiptGoodsVoucher( List<KingDeeOrderGoodsReceived> ogreList) {
        log.info("收货生成凭证（云平台、转采）  app:{}", ogreList);

        // 转采商品
        Set<KingDeeOrderGoodsReceived> virtualOrg = ogreList.stream().filter(t -> t.getVirtual()).collect(Collectors.toSet());
        // 平台商品
        Set<KingDeeOrderGoodsReceived> trueOrg = ogreList.stream().filter(t -> !t.getVirtual()).collect(Collectors.toSet());


        // 总金额
        BigDecimal trueAmounts = BigDecimal.ZERO;
        // 转采总金额
        BigDecimal virAmounts = BigDecimal.ZERO;

        String parentOrgId = "";
        String customerName = "";
        String orgName = "";
        List<Voucher> voucherList = new ArrayList<>();

        for (KingDeeOrderGoodsReceived received : ogreList) {

            // 客户
            customerName = received.getCustomerName();
            // 供应商
            orgName = received.getOrgName();
            // 父组织或当前组织
            String parentCustomerName = received.getParentCustomerName();
            // 转采订单
            BigDecimal purchaseCostAmount = received.getPurchaseCostAmount();
            // 商品未税金额
            BigDecimal goodsAmount = received.getPreAmount();

            parentOrgId = getKingDeeCode(parentCustomerName);

            // 真实供应商的订单商品
            if (null == received.getVirtual() || !received.getVirtual()) {
                Voucher tdv = Voucher.builder()
                        .business_id(String.valueOf(received.getId()))
                        .business_type(BusinessType.Receipt)
                        .remark("采购入库-" + orgName)
                        .ad_coding(String.valueOf(received.getVendorId()))
                        .ad_status(AccountingDimensionEnum.Vendor)
                        .subject_coding(FAccountIdEnum.payable0302.getFNumber())
                        .credit_amount(goodsAmount)
                        .account_name(ogreList.get(0).getAccountName())
                        .debit_amount(BigDecimal.ZERO)
                        //.createdTime(new Date())
                        .del(false)
                        .version("0")
                        .build();
                voucherList.add(tdv);

                Voucher tdc = Voucher.builder()
                        .business_id(String.valueOf(received.getId()))
                        .business_type(BusinessType.Receipt)
                        .remark("采购入库")
                        .subject_coding(FAccountIdEnum.stock01.getFNumber())
                        .credit_amount(BigDecimal.ZERO)
                        .debit_amount(goodsAmount)
                        .account_name(received.getAccountName())
                        //.createdTime(new Date())
                        .del(false)
                        .version("0")
                        .build();
                voucherList.add(tdc);

                trueAmounts = trueAmounts.add( goodsAmount);

            } else {
                Voucher vdv = Voucher.builder()
                        .business_id(String.valueOf(received.getId()))
                        .business_type(BusinessType.TransferOrder)
                        .remark("采购入库")
                        .subject_coding(FAccountIdEnum.payable0102.getFNumber())
                        .credit_amount(purchaseCostAmount)
                        .debit_amount(BigDecimal.ZERO)
                        .account_name(received.getAccountName())
                        //.createdTime(new Date())
                        .del(false)
                        .version("0")
                        .build();
                voucherList.add(vdv);

                Voucher vdc = Voucher.builder()
                        .business_id(String.valueOf(received.getId()))
                        .business_type(BusinessType.TransferOrder)
                        .remark("采购入库")
                        .subject_coding(FAccountIdEnum.stock02.getFNumber())
                        .credit_amount(BigDecimal.ZERO)
                        .debit_amount(purchaseCostAmount)
                        .account_name(received.getAccountName())
                        //.createdTime(new Date())
                        .del(false)
                        .version("0")
                        .build();
                voucherList.add(vdc);
                virAmounts = virAmounts.add(purchaseCostAmount);
            }
        }

        String oids = "";
        // 平台订单 贷
        if (null != trueOrg && !trueOrg.isEmpty()) {

            // 拼接客户订单号和供应商订单号
            Set<String> ids = trueOrg.stream().map(t -> t.getId()).collect(Collectors.toSet());

            // 客户订单号拼接
            oids = StringUtils.join(ids, ",");

            Voucher tsv = Voucher.builder()
                    .business_id(oids)
                    .business_type(BusinessType.Receipt)
                    .remark("销售出库")
                    .subject_coding(FAccountIdEnum.stock01.getFNumber())
                    .debit_amount(BigDecimal.ZERO)
                    .credit_amount(trueAmounts)
                    .account_name(ogreList.get(0).getAccountName())
                    //.createdTime(new Date())
                    .del(false)
                    .version("0")
                    .build();
            voucherList.add(tsv);

            Voucher tsc = Voucher.builder()
                    .business_id(oids)
                    .business_type(BusinessType.Receipt)
                    .remark("销售出库-" + customerName)
                    .ad_coding(parentOrgId)
                    .ad_status(AccountingDimensionEnum.Customer)
                    .subject_coding(FAccountIdEnum.release01.getFNumber())
                    .debit_amount(trueAmounts)
                    .credit_amount(BigDecimal.ZERO)
                    .account_name(ogreList.get(0).getAccountName())
                    //.createdTime(new Date())
                    .del(false)
                    .version("0")
                    .build();
            voucherList.add(tsc);
        }

        // 转采订单 贷
        if (null != virtualOrg && !virtualOrg.isEmpty()) {

            // 拼接客户订单号和供应商订单号
            Set<String> ids = virtualOrg.stream().map(t -> t.getId()).collect(Collectors.toSet());

            // 客户订单号拼接
            oids = StringUtils.join(ids, ",");

            Voucher vsv = Voucher.builder()
                    .business_id(oids)
                    .business_type(BusinessType.TransferOrder)
                    .remark("销售出库")
                    .subject_coding(FAccountIdEnum.stock02.getFNumber())
                    .debit_amount(BigDecimal.ZERO)
                    .credit_amount(virAmounts)
                    .account_name(ogreList.get(0).getAccountName())
                    //.createdTime(new Date())
                    .del(false)
                    .version("0")
                    .build();
            voucherList.add(vsv);

            Voucher vsc = Voucher.builder()
                    .business_id(oids)
                    .business_type(BusinessType.TransferOrder)
                    .remark("销售出库-" + customerName)
                    .ad_coding(parentOrgId)
                    .ad_status(AccountingDimensionEnum.Customer)
                    .subject_coding(FAccountIdEnum.release02.getFNumber())
                    .debit_amount(virAmounts)
                    .credit_amount(BigDecimal.ZERO)
                    .account_name(ogreList.get(0).getAccountName())
                    //.createdTime(new Date())
                    .del(false)
                    .version("0")
                    .build();
            voucherList.add(vsc);
        }

        //todo 批量保存 凭证信息
        List<Voucher> vouchers = saveVoucherList(voucherList);
        log.info("收货生成凭证  业务逻辑处理结束 <<<");

        return SingleResponse.of(vouchers);
    }


    /**
     * 退货生成凭证
     * 退平台：3.2销售退货、退供应商：2.2外购退货和3.2销售退货
     * 转采：销售退货
     * @param kingDeeReturnGeneration
     * @return
     */
    public SingleResponse returnGoodsVoucher( KingDeeReturnGeneration kingDeeReturnGeneration) {
        log.info("退货生成凭证  app:{}", "kingDeeReturnGeneration");

        KingDeeOrderGoodsRefund o = kingDeeReturnGeneration.getRefund();
        boolean Pm = kingDeeReturnGeneration.getPm();

        String oid = o.getId();
        // 此次商品退货（未税）金额
        BigDecimal goodsAmount = o.getGoodsAmount();
        // 转采退货金额
        BigDecimal purchaseCostAmount = o.getPurchaseAmount();
        // 客户名称
        String customerOrgName = o.getCustomerOrgName();
        // 客户父组织
        String parentCustomerOrgName = o.getParentCustomerOrgName();
        // 客户父组织如果为空就取客户组织
        String prentOrg = parentCustomerOrgName == "" ? customerOrgName : parentCustomerOrgName;
        // 通过客户名称查询 中间表金蝶编码
        String prentCustomerName = getKingDeeCode(prentOrg);

        // 供应商DI
        String vendorId = o.getVendorId();
        // 供应商名称
        String vendorName = o.getVendorName();

        List<Voucher> voucherList = new ArrayList<>();

        if (null == o.getVirtual() || !o.getVirtual()) {

            Voucher pdc = Voucher.builder()
                    .business_id(String.valueOf(oid))
                    .business_type(BusinessType.ReturnOrder)
                    .remark("销售退货-" + customerOrgName)
                    .ad_coding(prentCustomerName)
                    .ad_status(AccountingDimensionEnum.Customer)
                    .subject_coding(FAccountIdEnum.release01.getFNumber())
                    .debit_amount(goodsAmount.negate())
                    .credit_amount(BigDecimal.ZERO)
                    .account_name(kingDeeReturnGeneration.getAccountName())
                    .del(false)
                    .version("0")
                    .build();
            voucherList.add(pdc);

            Voucher sc = Voucher.builder()
                    .business_id(String.valueOf(oid))
                    .business_type(BusinessType.ReturnOrder)
                    .remark("销售退货")
                    .subject_coding(FAccountIdEnum.stock01.getFNumber())
                    .debit_amount(BigDecimal.ZERO)
                    .credit_amount(goodsAmount.negate())
                    .account_name(kingDeeReturnGeneration.getAccountName())
                    .del(false)
                    .version("0")
                    .build();
            voucherList.add(sc);

            //退货有选择退平台还是供应商，这个代表是否退平台
            if (!Pm) {
                //退供应商
                Voucher dv = Voucher.builder()
                        .business_id(String.valueOf(oid))
                        .business_type(BusinessType.ReturnOrder)
                        .remark("采购退货-" + vendorName)
                        .ad_coding(vendorId)
                        .ad_status(AccountingDimensionEnum.Vendor)
                        .subject_coding(FAccountIdEnum.payable0302.getFNumber())
                        .debit_amount(BigDecimal.ZERO)
                        .credit_amount(goodsAmount.negate())
                        .account_name(kingDeeReturnGeneration.getAccountName())
                        .del(false)
                        .version("0")
                        .build();
                voucherList.add(dv);

                Voucher sv = Voucher.builder()
                        .business_id(String.valueOf(oid))
                        .business_type(BusinessType.ReturnOrder)
                        .remark("采购退货")
                        .subject_coding(FAccountIdEnum.stock01.getFNumber())
                        .debit_amount(goodsAmount.negate())
                        .credit_amount(BigDecimal.ZERO)
                        .account_name(kingDeeReturnGeneration.getAccountName())
                        .del(false)
                        .version("0")
                        .build();
                voucherList.add(sv);
            }
        } else {
            // 转采订单退货
            // 销售退货3.2
            Voucher zcd = Voucher.builder()
                    .business_id(String.valueOf(oid))
                    .business_type(BusinessType.TransferReturnOrder)
                    .remark("销售退货-" + customerOrgName)
                    .ad_coding(prentCustomerName)
                    .ad_status(AccountingDimensionEnum.Customer)
                    .subject_coding(FAccountIdEnum.release02.getFNumber())
                    .debit_amount(purchaseCostAmount.negate())
                    .credit_amount(BigDecimal.ZERO)
                    .account_name(kingDeeReturnGeneration.getAccountName())
                    .del(false)
                    .version("0")
                    .build();
            voucherList.add(zcd);

            Voucher zcj = Voucher.builder()
                    .business_id(String.valueOf(oid))
                    .business_type(BusinessType.TransferReturnOrder)
                    .remark("销售退货")
                    .subject_coding(FAccountIdEnum.stock02.getFNumber())
                    .debit_amount(BigDecimal.ZERO)
                    .credit_amount(purchaseCostAmount.negate())
                    .account_name(kingDeeReturnGeneration.getAccountName())
                    .del(false)
                    .version("0")
                    .build();
            voucherList.add(zcj);
        }

        List<Voucher> vouchers = saveVoucherList(voucherList);
        log.info("订单退货 生成凭证 voucher:{}",vouchers);
        log.info("订单退货 生成凭证  业务逻辑处理结束 <<<");

        return SingleResponse.buildSuccess();
    }

}
